rm(list=ls())
library(tidyverse)
library(haven)

# Read margin of victory
margin_of_victories <- read_rds(here::here("data","processed","elections","margin_of_victories.rds"))
margin_of_victories <- margin_of_victories %>% 
  rename(year = ano_eleicao)

# Read fiscal outcomes
fiscal_outcomes <- read_rds(here::here("data","processed","fiscalpolicy","fiscal_outcomes_centered.rds"))

# Read Tiebout 
h_tiebout <- read_rds(here::here("data","processed","citycharacteristics","h_tiebout.rds"))
h_tiebout <- h_tiebout %>% 
  select(-mun_name)

# Read Bolsa Familia
bf_outcomes <- read_rds(here::here("data","processed","citycharacteristics","bolsa_fam.rds"))

# Read educational outcomes
educational_outcomes <- read_rds(here::here("data","processed","welfare_outcomes","educational_outcomes.rds"))

# Read Violence outcomes
violence_outcomes <- read_rds(here::here("data","processed","welfare_outcomes","violence_outcomes.rds"))

# Read health outcomes
health_outcomes <- read_rds(here::here("data","processed","welfare_outcomes","health_outcomes.rds"))

# Read Amendments outcomes
amendments_outcomes <- read_rds(here::here("data","processed","citycharacteristics","amendments_outcomes.rds"))

# Join all databases

main_database <- margin_of_victories %>%
  left_join(fiscal_outcomes, by = c("mun_code","year")) %>% 
  left_join(h_tiebout, by = c("mun_code")) %>% 
  left_join(bf_outcomes, by = c("mun_code","year")) %>% 
  left_join(educational_outcomes, by = c("mun_code","year")) %>% 
  left_join(violence_outcomes, by = c("mun_code","year")) %>%
  left_join(health_outcomes, by = c("mun_code","year")) %>%
  left_join(amendments_outcomes, by = c("mun_code","year")) 

# Create Geographic regions

main_database <- main_database %>% 
  mutate(state = str_sub(mun_code,1,2),
         north = ifelse(state %in% c(11:17),1,0),
         northeast = ifelse(state %in% c(21:29),1,0),
         southeast = ifelse(state %in% c(31:35),1,0),
         south = ifelse(state %in% c(41:43),1,0),
         midwest = ifelse(state %in% c(50:53),1,0))

# Replace NA to zero in the case of amendments
main_database <- main_database %>% 
  mutate(across(contains("amendment"),
                ~ifelse(is.na(.),0,.)))

# Save ------
write_dta(main_database,here::here("data","processed","main_database.dta"))


